<?php

namespace AntStudio\AntToolsSdk\common;
/**
 * Curl请示类
 */
class RequestFun
{
    /**
     * 模拟post进行url请求
     * @param $url
     * @param $param
     * @return bool|string
     */
    function post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $ch = curl_init();                   //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url); //抓取指定网页
        curl_setopt($ch, CURLOPT_POST, 1);   //post提交方式
        if ($param != '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HEADER, false);         //设置header
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);

        return $data;
    }

    /**
     * file_get_contents 请求
     * @param $url
     * @return bool|string
     */
    function fileGetContent($url)
    {
        if (function_exists('file_get_contents')) {
            $file_contents = @file_get_contents($url);
        }
        if ($file_contents == '') {
            $ch      = curl_init();
            $timeout = 30;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        }

        return $file_contents;
    }

    /**
     * 模拟请求-带头部
     * @param $url
     * @param $post_data
     * @return false|string
     */
    function sendPost($url, $post_data)
    {
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/json', //header 需要设置为 JSON
                'content' => $post_data,
                'timeout' => 60, //超时时间
            ),
        );
        //'header' => 'Content-type:application/x-www-form-urlencoded', //header 需要设置为 JSON
        $context = @stream_context_create($options);
        $result  = @file_get_contents($url, false, $context);

        return $result;
    }
}